<template>
  <div class="parking-container">
    <el-card class="page-header-card">
      <div class="page-header">
        <div class="page-title">
          <h2>停车场</h2>
          <p>查看停车场状态和车位信息</p>
        </div>
      </div>
    </el-card>
    
    <!-- 停车场选择器和总览 -->
    <el-row :gutter="20">
      <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
        <el-card class="lot-select-card">
          <el-select 
            v-model="selectedLotId" 
            placeholder="请选择停车场"
            @change="handleLotChange"
            style="width: 240px;"
          >
            <el-option 
              v-for="lot in parkingLots" 
              :key="lot.id" 
              :label="lot.name" 
              :value="lot.id"
            />
          </el-select>
          
          <div v-if="selectedLotInfo" class="lot-info">
            <div class="lot-info-item">
              <span class="info-label">开放时间:</span>
              <span class="info-value">{{ selectedLotInfo.openTime.substring(0, 5) }} - {{ selectedLotInfo.closeTime.substring(0, 5) }}</span>
            </div>
            <div class="lot-info-item">
              <span class="info-label">联系电话:</span>
              <span class="info-value">{{ selectedLotInfo.contactPhone }}</span>
            </div>
            <div class="lot-info-item">
              <span class="info-label">状态:</span>
              <el-tag :type="selectedLotInfo.status === 1 ? 'success' : 'danger'">
                {{ selectedLotInfo.status === 1 ? '开放中' : '已关闭' }}
              </el-tag>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <div v-if="!selectedLotId" class="empty-placeholder">
      <el-empty description="请选择停车场"></el-empty>
    </div>
    
    <template v-else>
      <!-- 停车场统计信息 -->
      <el-row :gutter="20" v-if="parkingStats">
        <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
          <el-card class="stats-card">
            <div class="stats-overview">
              <div class="stat-box">
                <div class="stat-value">{{ parkingStats.total }}</div>
                <div class="stat-label">总车位</div>
              </div>
              <div class="stat-box available">
                <div class="stat-value">{{ parkingStats.statusCount.available }}</div>
                <div class="stat-label">可用车位</div>
              </div>
              <div class="stat-box occupied">
                <div class="stat-value">{{ parkingStats.statusCount.occupied }}</div>
                <div class="stat-label">已占用</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
      
      
      
      <!-- 车位地图 -->
      <el-row :gutter="20">
        <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
          <el-card class="space-map-card" v-loading="mapLoading">
            <template #header>
              <div class="card-header">
                <span>车位地图</span>
                <div class="card-legend">
                  <div class="legend-item">
                    <div class="legend-color available"></div>
                    <span>空闲</span>
                  </div>
                  <div class="legend-item">
                    <div class="legend-color occupied"></div>
                    <span>已占用</span>
                  </div>
                  <div class="legend-item">
                    <div class="legend-color reserved"></div>
                    <span>已预约</span>
                  </div>
                  <div class="legend-item">
                    <div class="legend-color maintenance"></div>
                    <span>维护中</span>
                  </div>
                </div>
              </div>
            </template>
            
            <!-- 空数据显示 -->
            <div v-if="parkingSpaces.length === 0" class="space-map-empty">
              <el-empty description="暂无车位数据"></el-empty>
            </div>
            <!-- 车位地图显示 -->
            <template v-else>
              <div class="space-map">
                <div class="map-grid">
                  <div v-for="area in uniqueAreas" :key="area" class="area-section">
                    <div class="area-title">{{ area }}区</div>
                    <div class="area-spaces">
                      <div
                        v-for="space in getSpacesByArea(area)"
                        :key="space.id"
                        class="space-item"
                        :class="getSpaceClass(space)"
                        @click="showSpaceDetail(space)"
                      >
                        <span class="space-number">{{ space.spaceNumber }}</span>
                        <span class="space-type">{{ getSpaceTypeName(space.spaceType) }}</span>
                        <div class="space-status-icon">
                          <el-icon v-if="space.status === 1"><Lock /></el-icon>
                          <el-icon v-else-if="space.status === 2"><Tools /></el-icon>
                          <el-icon v-else-if="space.status === 3"><Timer /></el-icon>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </template>
          </el-card>
        </el-col>
      </el-row>
      
      <!-- 车位列表 -->
      <el-row :gutter="20">
        <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
          <el-card class="space-list-card">
            <template #header>
              <div class="card-header">
                <span>车位列表</span>
                <el-input 
                  v-model="spaceNumber" 
                  placeholder="搜索车位编号" 
                  clearable
                  style="width: 200px;"
                >
                  <template #append>
                    <el-button :icon="Search" @click="searchSpaces"></el-button>
                  </template>
                </el-input>
              </div>
            </template>
            
            <el-table 
              :data="filteredSpaces" 
              style="width: 100%" 
              v-loading="tableLoading"
              :empty-text="parkingSpaces.length ? '找不到匹配的车位' : '暂无车位数据'"
            >
              <el-table-column prop="spaceNumber" label="车位编号" width="120" />
              <el-table-column prop="area" label="区域" width="100" />
              <el-table-column prop="floor" label="楼层" width="100" />
              <el-table-column label="类型" width="100">
                <template #default="scope">
                  <el-tag :type="getSpaceTypeTag(scope.row.spaceType)">
                    {{ getSpaceTypeName(scope.row.spaceType) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="状态" width="100">
                <template #default="scope">
                  <el-tag :type="getSpaceStatusTag(scope.row.status)">
                    {{ getSpaceStatusName(scope.row.status) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="120">
                <template #default="scope">
                  <el-button 
                    v-if="scope.row.status === 0" 
                    type="primary" 
                    link
                    @click="goReservation(scope.row)"
                  >预约</el-button>
                  <el-button 
                    type="info" 
                    link
                    @click="showSpaceDetail(scope.row)"
                  >详情</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-col>
      </el-row>
    </template>
    
    <!-- 车位详情弹窗 -->
    <el-dialog
      v-model="spaceDetailVisible"
      title="车位详情"
      width="400px"
      destroy-on-close
    >
      <div v-if="selectedSpace" class="space-detail">
        <div class="detail-item">
          <span class="detail-label">车位编号：</span>
          <span class="detail-value">{{ selectedSpace.spaceNumber || '-' }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">所属区域：</span>
          <span class="detail-value">{{ selectedSpace.area || '-' }}区</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">所在楼层：</span>
          <span class="detail-value">{{ selectedSpace.floor || '-' }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">车位类型：</span>
          <el-tag size="small" :type="getSpaceTypeTag(selectedSpace.spaceType)">
            {{ getSpaceTypeName(selectedSpace.spaceType) }}
          </el-tag>
        </div>
        <div class="detail-item">
          <span class="detail-label">当前状态：</span>
          <el-tag size="small" :type="getSpaceStatusTag(selectedSpace.status)">
            {{ getSpaceStatusName(selectedSpace.status) }}
          </el-tag>
        </div>
        <div v-if="selectedSpace.status === 1" class="detail-item">
          <span class="detail-label">占用车辆：</span>
          <span class="detail-value">{{ selectedSpace.plateNumber || '无牌照' }}</span>
        </div>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="spaceDetailVisible = false">关闭</el-button>
          <el-button 
            v-if="selectedSpace && selectedSpace.status === 0" 
            type="primary" 
            @click="goReservation(selectedSpace)"
          >预约此车位</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Search, Lock, Tools, Timer } from '@element-plus/icons-vue'
import { 
  getParkingLotList, 
  getParkingLotDetail, 
  getParkingSpaceList, 
  getParkingLotStats 
} from '@/api/parking'

// 路由实例
const router = useRouter()

// 停车场数据
const parkingLots = ref([])
const selectedLotId = ref(null)
const selectedLotInfo = ref(null)

// 车位数据
const parkingSpaces = ref([])
const filteredSpaces = ref([])
const parkingStats = ref(null)
const selectedSpace = ref(null)
const spaceDetailVisible = ref(false)

// 筛选条件
const selectedArea = ref('')
const selectedFloor = ref('')
const selectedSpaceType = ref('')
const searchNumber = ref('')

// 加载状态
const listLoading = ref(false)
const mapLoading = ref(false)
const tableLoading = ref(false)

// 获取停车场列表
const fetchParkingLots = async () => {
  listLoading.value = true;
  try {
    const res = await getParkingLotList();
    // 处理分页数据，获取records字段（存放实际数据的数组）
    parkingLots.value = res.data.records || [];
    
    // 默认选中第一个停车场，但只在列表非空且当前没有选中值时
    if (parkingLots.value.length > 0 && !selectedLotId.value) {
      selectedLotId.value = parkingLots.value[0].id;
      if (selectedLotId.value) {
        await handleLotChange(selectedLotId.value);
      }
    } else if (parkingLots.value.length === 0) {
      // 如果没有停车场数据，重置所有相关状态
      selectedLotId.value = null;
      selectedLotInfo.value = null;
      parkingStats.value = null;
      parkingSpaces.value = [];
      filteredSpaces.value = [];
    }
  } catch (error) {
    console.error('获取停车场列表失败:', error);
    ElMessage.error('获取停车场列表失败');
    // 发生错误时，重置所有相关状态
    parkingLots.value = [];
    selectedLotId.value = null;
    selectedLotInfo.value = null;
    parkingStats.value = null;
    parkingSpaces.value = [];
    filteredSpaces.value = [];
  } finally {
    listLoading.value = false;
  }
}

// 获取停车场详情
const fetchParkingLotDetail = async (id) => {
  if (!id) return;
  
  try {
    const res = await getParkingLotDetail(id);
    selectedLotInfo.value = res.data;
  } catch (error) {
    console.error('获取停车场详情失败:', error);
    ElMessage.error('获取停车场详情失败');
  }
}

// 获取停车场统计信息
const fetchParkingLotStats = async (id) => {
  if (!id) return;
  
  try {
    const res = await getParkingLotStats(id);
    parkingStats.value = res.data;
  } catch (error) {
    console.error('获取停车场统计信息失败:', error);
    ElMessage.error('获取停车场统计信息失败');
  }
}

// 获取车位列表
const fetchParkingSpaces = async () => {
  // 如果没有选择停车场，不执行查询
  if (!selectedLotId.value) {
    parkingSpaces.value = [];
    filteredSpaces.value = [];
    mapLoading.value = false;
    tableLoading.value = false;
    return;
  }
  
  mapLoading.value = true;
  tableLoading.value = true;
  
  try {
    const params = {
      parkingLotId: selectedLotId.value,
      area: selectedArea.value || undefined,
      floor: selectedFloor.value || undefined,
      spaceType: selectedSpaceType.value !== '' ? selectedSpaceType.value : undefined
    };
    
    const res = await getParkingSpaceList(params);
    // 处理分页数据，确保获取records字段
    parkingSpaces.value = res.data.records || [];
    filteredSpaces.value = [...parkingSpaces.value];
  } catch (error) {
    console.error('获取车位列表失败:', error);
    ElMessage.error('获取车位列表失败');
    // 发生错误时，清空数据
    parkingSpaces.value = [];
    filteredSpaces.value = [];
  } finally {
    mapLoading.value = false;
    tableLoading.value = false;
  }
}

// 处理停车场切换
const handleLotChange = async (id) => {
  if (!id) {
    // 如果id为null或undefined，重置相关数据而不是尝试获取
    selectedLotInfo.value = null;
    parkingStats.value = null;
    parkingSpaces.value = [];
    filteredSpaces.value = [];
    return;
  }
  
  await fetchParkingLotDetail(id);
  await fetchParkingLotStats(id);
  await fetchParkingSpaces();
}

// 处理区域切换
const handleAreaChange = () => {
  fetchParkingSpaces()
}

// 处理楼层切换
const handleFloorChange = () => {
  fetchParkingSpaces()
}

// 处理类型切换
const handleTypeChange = () => {
  fetchParkingSpaces()
}

// 搜索车位
const searchSpaces = () => {
  tableLoading.value = true
  
  setTimeout(() => {
    if (!searchNumber.value) {
      filteredSpaces.value = [...parkingSpaces.value]
    } else {
      filteredSpaces.value = parkingSpaces.value.filter(space => 
        space.spaceNumber.toLowerCase().includes(searchNumber.value.toLowerCase())
      )
    }
    tableLoading.value = false
  }, 200)
}

// 显示车位详情
const showSpaceDetail = (space) => {
  selectedSpace.value = space
  spaceDetailVisible.value = true
}

// 前往预约页面
const goReservation = (space) => {
  router.push({
    path: '/user/reservation',
    query: {
      spaceId: space.id,
      spaceNumber: space.spaceNumber
    }
  })
}

// 获取车位状态类名
const getSpaceClass = (space) => {
  const classes = [];
  switch (space.status) {
    case 0:
      classes.push('available');
      break;
    case 1:
      classes.push('occupied');
      break;
    case 2:
      classes.push('maintenance');
      break;
    case 3:
      classes.push('reserved');
      break;
  }
  return classes;
}

// 获取车位状态标签类型
const getSpaceStatusTag = (status) => {
  switch (status) {
    case 0: return 'success'
    case 1: return 'info'
    case 2: return 'danger'
    case 3: return 'warning'
    default: return 'info'
  }
}

// 获取车位状态名称
const getSpaceStatusName = (status) => {
  switch (status) {
    case 0: return '空闲'
    case 1: return '已占用'
    case 2: return '维护中'
    case 3: return '已预约'
    default: return '未知状态'
  }
}

// 获取车位类型标签类型
const getSpaceTypeTag = (type) => {
  switch (Number(type)) {
    case 0: return ''
    case 1: return 'success'
    case 2: return 'warning'
    default: return 'info'
  }
}

// 获取车位类型名称
const getSpaceTypeName = (type) => {
  switch (Number(type)) {
    case 0: return '普通车位'
    case 1: return '固定车位'
    case 2: return '访客车位'
    default: return '未知类型'
  }
}

// 获取车位样式
const getSpaceStyle = (space) => {
  const cellSize = 60
  
  return {
    left: `${space.positionX * cellSize}px`,
    top: `${space.positionY * cellSize}px`,
    width: `${cellSize - 6}px`,
    height: `${cellSize - 6}px`
  }
}

// 获取所有唯一的区域
const uniqueAreas = computed(() => {
  return [...new Set(parkingSpaces.value.map(space => space.area))].sort();
});

// 根据区域获取车位
const getSpacesByArea = (area) => {
  return parkingSpaces.value.filter(space => space.area === area);
};

// 组件挂载时获取数据
onMounted(() => {
  fetchParkingLots()
})
</script>

<style scoped>
.parking-container {
  min-height: calc(100vh - 180px);
}

.page-header-card {
  margin-bottom: 20px;
  background: linear-gradient(135deg, #3f51b5, #3949ab);
  color: white;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-title h2 {
  margin: 0;
  font-size: 24px;
}

.page-title p {
  margin: 8px 0 0;
  opacity: 0.8;
  font-size: 14px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
}

.lot-select-card {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.lot-info {
  display: flex;
  align-items: center;
  margin-left: 20px;
}

.lot-info-item {
  margin-right: 20px;
  display: flex;
  align-items: center;
}

.info-label {
  margin-right: 5px;
  color: #909399;
}

.empty-placeholder {
  min-height: 300px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.stats-card {
  margin-bottom: 20px;
}

.stats-overview {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
}

.stat-box {
  text-align: center;
  padding: 15px;
  border-radius: 8px;
  background-color: #f5f7fa;
  flex: 1;
  min-width: 120px;
  margin: 0 10px 10px 0;
}

.stat-value {
  font-size: 32px;
  font-weight: bold;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: #606266;
}

.stat-box.available {
  background-color: #f0f9eb;
}

.stat-box.available .stat-value {
  color: #67c23a;
}

.stat-box.occupied {
  background-color: #f4f4f5;
}

.stat-box.occupied .stat-value {
  color: #909399;
}

.stat-box.reserved {
  background-color: #fdf6ec;
}

.stat-box.reserved .stat-value {
  color: #e6a23c;
}

.stat-box.maintenance {
  background-color: #fef0f0;
}

.stat-box.maintenance .stat-value {
  color: #f56c6c;
}

.stat-box.rate {
  background-color: #ecf5ff;
}

.stat-box.rate .stat-value {
  color: #409eff;
}

.filter-card {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}

.filter-card .el-radio-group {
  margin: 8px 0;
}

.space-map-card {
  margin-bottom: 20px;
  min-height: 400px;
}

.card-legend {
  display: flex;
  align-items: center;
}

.legend-item {
  display: flex;
  align-items: center;
  margin-left: 15px;
  font-weight: normal;
}

.legend-color {
  width: 20px;
  height: 12px;
  border-radius: 2px;
  margin-right: 5px;
}

.legend-color.available {
  background-color: #67c23a;
}

.legend-color.occupied {
  background-color: #909399;
}

.legend-color.reserved {
  background-color: #e6a23c;
}

.legend-color.maintenance {
  background-color: #f56c6c;
}

.space-map-empty {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 300px;
}

.space-map {
  padding: 20px;
}

.map-grid {
  display: flex;
  flex-direction: column;
  gap: 30px;
}

.area-section {
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.area-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #dcdfe6;
  color: #303133;
}

.area-spaces {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
  gap: 20px;
  padding: 10px;
}

.space-item {
  height: 80px;
  border-radius: 8px;
  color: white;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  transition: all 0.3s;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  position: relative;
  padding: 10px;
  text-align: center;
}

.space-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
}

.space-number {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 6px;
  display: block;
  width: 100%;
  text-align: center;
  color: #ffffff;
}

.space-type {
  font-size: 12px;
  background-color: rgba(255, 255, 255, 0.2);
  padding: 2px 8px;
  border-radius: 4px;
  display: block;
  width: calc(100% - 16px);
  text-align: center;
  color: #ffffff;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.space-status-icon {
  position: absolute;
  top: 8px;
  right: 8px;
  font-size: 16px;
}

/* 车位状态颜色 */
.space-item.available {
  background-color: #67c23a;
}

.space-item.occupied {
  background-color: #909399;
}

.space-item.reserved {
  background-color: #e6a23c;
}

.space-item.maintenance {
  background-color: #f56c6c;
}

.space-list-card {
  margin-bottom: 20px;
}

.space-detail {
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 8px;
}

.detail-item {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.detail-item:last-child {
  margin-bottom: 0;
}

.detail-label {
  width: 100px;
  color: #606266;
  font-size: 14px;
}

.detail-value {
  font-weight: 500;
  color: #303133;
  font-size: 14px;
}

@media screen and (max-width: 768px) {
  .lot-select-card {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .lot-info {
    margin-left: 0;
    margin-top: 15px;
    flex-direction: column;
    align-items: flex-start;
  }
  
  .lot-info-item {
    margin-right: 0;
    margin-bottom: 10px;
  }
  
  .filter-card {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .filter-card .el-radio-group {
    margin: 10px 0;
    max-width: 100%;
    overflow-x: auto;
  }
  
  .filter-card .el-divider--vertical {
    display: none;
  }
  
  .card-header {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .card-header .el-input {
    margin-top: 10px;
    width: 100% !important;
  }
  
  .card-legend {
    margin-top: 10px;
    flex-wrap: wrap;
  }
  
  .legend-item {
    margin-left: 0;
    margin-right: 15px;
    margin-bottom: 5px;
  }
  
  .space-item {
    font-size: 10px;
  }
}
</style> 